import { Input, Checkbox, Button, message, Alert } from 'antd'
import ChooseGroups from '@/desktop/components/ChooseGroups'
import { modalFooter } from '@/desktop/styles/theme'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { BaseGroup } from '@/services/contact-types'
import './Content.module.less'

export default function Content(props: { onClose: () => void }) {
  const { onClose } = props

  const [groupMap] = useStreams(services.groups.list)

  const [choosed, setChoosed] = useState<string[]>([])
  const [text, setText] = useState('')

  const [includeInternal, setIncludeInternal] = useState(true)
  const [includeExternal, setIncludeExternal] = useState(true)
  const switchIncludeInternal = useCallback(() => setIncludeInternal(v => !v), [])
  const switchIncludeExternal = useCallback(() => setIncludeExternal(v => !v), [])
  const filter = useCallback(
    (group: BaseGroup) => {
      if (
        (group.isExternal && !includeExternal) ||
        (!group.isExternal && !includeInternal) ||
        !group.isOwner // 目前只支持由群主发送（底层支持由管理员发送，但因为无法判断是不是管理员，所以前端不支持）
      )
        return false
      return true
    },
    [includeInternal, includeExternal],
  )

  // ============================================

  const [submitting, setSubmitting] = useState(false)

  const submit = useCallback(async () => {
    setSubmitting(true)
    await services.groups.updateNotice(
      text,
      choosed.map(id => {
        const group = groupMap.get(id)!
        return { conversationId: group.conversationId, ownerWxid: group.ownerWxid }
      }),
    )
    void message.success('发送完成')
    setSubmitting(false)
    onClose()
  }, [choosed, groupMap, text, onClose])

  // ============================================

  const filterView = <div styleName="scope">
    <label>筛选：</label>
    <Checkbox checked={includeInternal} onClick={switchIncludeInternal}>
      内部群
    </Checkbox>
    <Checkbox checked={includeExternal} onClick={switchIncludeExternal}>
      外部群
    </Checkbox>
  </div>

  const formView = <div styleName="form">
    <Alert type="info" message="目前仅支持由群主发布群公告" css={{ marginBottom: '20px' }} />

    <header>公告内容</header>
    <Input.TextArea
      placeholder="请填写群公告内容"
      autoSize={{ minRows: 6, maxRows: 6 }}
      value={text}
      onChange={e => setText(e.target.value)}
    />
  </div>

  const submitView = <footer css={modalFooter}>
    <Button
      disabled={!choosed.length || !text}
      loading={submitting}
      type="primary"
      onClick={submit}
    >
      发送
    </Button>
  </footer>

  return <div styleName="content">
    <ChooseGroups
      choosed={choosed}
      setChoosed={setChoosed}
      filter={filter}
      filterView={filterView}
      choosedPrefix={formView}
      choosedSuffix={submitView}
    />
  </div>
}
